<?php
// $Id: tcprofile_search.page.inc,v 1.0 2010/08/18 12:48:18 llin Exp $

/**
 * provide general/advanced view of user info (more info)
 * @param Int $uid 
 */
function tcprofile_search_view($uid) {
  global $user;
  $output = '';
  if (user_access('view advanced tc profile search', $user)) {
    $result = db_query("SELECT f.category, f.title, v.value, f.name FROM {profile_fields} f, {profile_values} v WHERE f.fid = v.fid AND v.uid = %d", $uid);  
    $search_type = 'advanced';
  }
  else {
    $result = db_query("SELECT f.category, f.title, v.value, f.name FROM {profile_fields} f, {profile_values} v WHERE f.fid = v.fid AND v.uid = %d AND f.visibility != 1 AND f.visibility != 4", $uid);
    $search_type = 'general';
  }

  // user profile field visibility setup
  $fields_not_to_show = array();
  $field_result = db_query("SELECT * FROM {tcprofile_field_setup} WHERE uid = " . $uid);
  while ($field_row = db_fetch_array($field_result)) {
    $fields_not_to_show = explode(',', $field_row['selected_fields']);
  }

  // user pic
  $viewed_user = user_load($uid);

  if (!empty($viewed_user->picture)) {
    $output = theme('image', $viewed_user->picture, $viewed_user->name, $viewed_user->name) . "<br />";
  }

  // user data row, start from user id then profile fields
  $rows = array();
  $rows[] = array('ID', $viewed_user->name);

  // then user's roles
  $roles = array();
  foreach($viewed_user->roles as $role_name) {
    $roles[] = $role_name;  
  }
  $rows[] = array('ROLES', implode(', ', $roles));

  while ($row = db_fetch_array($result)) {
    if (!in_array($row['name'], $fields_not_to_show))
      $rows[] = array($row['title'], $row['value']);
  }
  if (count($rows) > 0) {
    db_query("INSERT INTO {tcprofile_search_log} (viewer_uid, viewee_uid, timestamp) VALUES (%d, %d, %d)", $user->uid, $uid, time());
    $header = array(
      t('Title'),
      t('Profile'),
    );
    $output .= theme('table', $header, $rows) . '<br />';      
  }

  // profile quiz 
  if ($search_type == 'advanced') {
    $rows = array();
    $result = db_query("SELECT DISTINCT nid FROM {node} WHERE uid = %d AND type = 'profile' LIMIT 0, 1", $uid);
    while ($row = db_fetch_array($result)) {
      $rows[] = $row['nid'];
    }

    if (count($rows) == 0 )
      $output .= _get_block_wrapper('profile_quiz', t('Profile Quiz'), '该会员还没有创建个人问卷');
    else
      $output .= _get_block_wrapper('profile_quiz', t('Profile Quiz'), '<a href="/node/' . $rows[0] . '">查看该会员个人问卷</a>'); 
  }

  // send this user a private msg
  $output .= _get_block_wrapper('privatemsg', t('Private messages'), '<a href="/messages/new/' . $uid . '">' . t('Send this user a message') . '</a>');

  // include a user relationship block
  if (user_access('view others relationships')) {
    $ur_block = module_invoke('user_relationship_blocks', 'block', 'view', 'actions');
    $output .= $ur_block['content'];
  }

  // for advanced view, show user's album
  if ($search_type == 'advanced') {
    if (function_exists('_photos_block_image')) {
      $count = variable_get('photos_block_num_1', 10);
      $content = _photos_block_image('user', $count, "photos/user/$uid/image", $uid);
      if (strlen(trim($content[0])) > 0) {
        $output .= _get_block_wrapper('album-photo', t('User\'s Album/Photo'), $content[0]);
      }
    }
  }
  else {
    $output .= variable_get('tcprofile_search_membership_upgrade_blurb', '');
  } 

  // report abuse user
  $flag_rows = array();
  $flag_result = db_query("SELECT DISTINCT fcid FROM {flag_content} WHERE fid = 2 AND content_type = 'user' AND content_id = %d AND uid = %d", $uid, $user->uid);
  while ($flag_row = db_fetch_array($flag_result)) {
    $flag_rows[] = $flag_row['fcid'];
  }

  if (count($flag_rows) == 0 )
    $output .= _get_block_wrapper('report_abuse', t('Report Abuse'), '<a href="/flag/confirm/flag/abuse_user/' . $uid . '?destination=' . str_replace('/', '%2F', substr($_SERVER['REQUEST_URI'], 1)) . '">Report this user as offensive</a>');
  else
    $output .= _get_block_wrapper('report_abuse', t('Report Abuse'), '<a href="/flag/confirm/unflag/abuse_user/' . $uid . '?destination=' . str_replace('/', '%2F', substr($_SERVER['REQUEST_URI'], 1)) . '">Revert the report of offensive</a>');

  // link to profile fields setup
  if (user_access('set profile field visibility'))
    $output .= '<br /><a href="/tcprofile/field_setup/' . $uid . '">Change profile fields visibility</a><br />'; 

  $output .= '<br /><a href="/tcprofile/email_notificaiton_setup/' . $uid . '">Change email notification setup</a><br />';

  // im control
  /*
  if (module_exists('imcontrol')) {
    require_once(drupal_get_path('module', 'imcontrol') . '/imcontrol.page.inc' );
    if (function_exists('imcontrol_page')) {
      $account = user_load($uid);
      $output .= _get_block_wrapper('imc', t('User\'s IM'), imcontrol_page($account));
    }
  }
  */

  return $output;      
} // function tcprofile_search_view

/**
 * get manual block wrapper
 * @param String $block_id
 * @param String $block_title
 * @param String $content
 * @return String $coutput
 */
function _get_block_wrapper($block_id, $block_title, $content) {
  $output = '';
  $output .= '<br /><div id="block-' . $block_id . '" class="block block-' . $block_id . '">' . "\n";
  $output .= ' <div class="inner">' . "\n";
  $output .= ' <h2>' . t($block_title) . '</h2>' . "\n";
  $output .= ' <div class="content">' . "\n";
  $output .= ' <div class="item-list"><ul><li class="first">' . "\n";
  $output .= $content;
  $output .= '</li></ul></div>';
  $output .= ' </div>' . "\n";
  $output .= ' </div>' . "\n";
  $output .= '</div>' . "\n";
  return $output;
} // function _get_block_wrapper

/**
 * @param String $search_type
 * @return Form
 */
function tcprofile_search_tease($search_type) {
  return variable_get('tcprofile_search_access_denied_blurb', t('Access denied.'));
} // function tcprofile_search_tease

/**
 * @param String $search_type
 * @return Form
 */
function tcprofile_search_form_ui($search_type) {
  return tcprofile_search_result($search_type) . drupal_get_form('tcprofile_search_get_search_form');
} // function tcprofile_search_form_ui

/**
 * @param String $search_type
 * @return Form
 */
function tcprofile_search_result($search_type) {
  $output = '';

  // get passed parameter value for the fields
  $profile_field_values = $_GET;

  // search by user name
  $username = isset($profile_field_values['username']) ? $profile_field_values['username'] : '';   
  $uids_by_username = tcprofile_search_by_username($username);

  // get searchable fields for this type, general or advanced
  $searchable_fields = variable_get('tcprofile_search_' . $search_type . '_fields', array(''));
  $uids_prev = array();
  $count = 0;
  $and_match = FALSE;
  foreach ($searchable_fields as $searchable_field) {
    $parameter_value = '';
    if ($searchable_fields[$searchable_field] && $profile_field_values[$searchable_field])
      $parameter_value = $profile_field_values[$searchable_field];
    if (!empty($parameter_value)) {
      $result = db_query("SELECT v.uid FROM {profile_fields} f, {profile_values} v WHERE f.fid = v.fid AND f.name = '%s' AND v.value LIKE '%%%s%%'", $searchable_field, $parameter_value);
      $uids = array();
      while ($row = db_fetch_array($result)) {
        // add whatever result in the first query
        // if it is AND, make sure it match the previous'
        if ($count == 0) 
          $uids[$row['uid']] = $row['uid'];
        elseif (in_array($row['uid'], $uids_prev)) {
          $uids[$row['uid']] = $row['uid'];
          $and_match = TRUE;
          //print $row['uid'] .  " SELECT v.uid FROM {profile_fields} f, {profile_values} v WHERE f.fid = v.fid AND f.name = '" . $searchable_field . "' AND v.value LIKE '%" . $parameter_value . "%'" . "<br />\r\n";
        }
      }
      unset($result);
      if (count($uids) > 0) {
        $uids_prev = $uids;
      }
      $count ++;
    }
  }

  // user name search and profile search is OR relation
  // once either has a result, it should showup 
  if (count($uids_by_username) > 0) {
    // if there are result from profile search, merge them
    if ($and_match) {
      $uids_prev = array_merge($uids_by_username, $uids_prev);
    }
    else {
      $uids_prev = $uids_by_username; 
      $and_match = TRUE;
    }
  }

  // the result from the first query is always saved
  // make sure it has and match, otherwise discard the result from first query
  $combo_sql = "SELECT DISTINCT u.uid, u.name, u.status, u.created, u.access FROM {users} u LEFT JOIN {users_roles} ur ON u.uid = ur.uid WHERE u.uid != 1 AND u.uid != 0 AND u.uid IN (" . implode(', ', $uids_prev) . ")" ;
  $query_count = "SELECT COUNT(DISTINCT u.uid) FROM {users} u LEFT JOIN {users_roles} ur ON u.uid = ur.uid WHERE u.uid != 1 AND u.uid != 0 AND u.uid IN (" . implode(', ', $uids_prev) . ")";
  $output = _get_table_list($combo_sql, $query_count, $and_match, $profile_field_values['form_id'], $search_type); 
  return $output;
} // function tcprofile_search_result

/**
 * return result by searching user name
 * @param String $username
 * @return Array uid
 */
function tcprofile_search_by_username ($username) {
  $uids = array();
  if (strlen($username) > 0) {
    // compose query
    $sql = "SELECT DISTINCT u.uid, u.name, u.status, u.created, u.access FROM {users} u LEFT JOIN {users_roles} ur ON u.uid = ur.uid WHERE u.uid != 0 AND u.uid != 1";
    $where = " AND UPPER(u.name) LIKE '%%%s%%'";
    $result = db_query($sql . $where, $username);
    while ($row = db_fetch_array($result)) {
      $uids[$row['uid']] = $row['uid'];
    }
  }
  return $uids;
} // function tcprofile_search_by_username

/**
 * @param String $search_type
 * @return Array $form
 */
function tcprofile_search_get_search_form() {
  $search_type = 'general';

  if (arg(1)) {
    $search_type = str_replace('_search', '', arg(1));
  }

  $collapsed = FALSE;
  $searchable_fields = variable_get('tcprofile_search_' . $search_type . '_fields', array(''));

  $form[$search_type] = array(
    '#type' => 'fieldset',
    '#title' => t(ucwords($search_type) . ' profile search'),
    '#collapsible' => TRUE,
    '#collapsed' => $collapsed,
    '#attributes' => array('class' => 'search-' . $search_type),
  );

  $form[$search_type]['username'] = array(
    '#type' => 'textfield',
    '#title' => t('User Name OR'),
    '#default_value' => isset($_GET['username']) ? $_GET['username'] : '',
    '#rows' => 1,
    '#size' => 10,  
  );

  $result = db_query("SELECT fid, title, name, type, category, options FROM {profile_fields} ORDER BY category, weight");
  $profile_field_values = $_GET;
  $previous_category = '';
  while ($row = db_fetch_array($result)) {
    if ($searchable_fields[$row['name']]) {
      if ($row['category'] != $previous_category) {
        $form[$search_type][$row['category']] = array(
          '#type' => 'fieldset',
          '#title' => $row['category'],
          '#collapsable' => FALSE,
        );
      }
      if ($row['type'] == 'selection') {
        $options_tmp = explode("\n", $row['options']);
        $options = array();
        foreach ($options_tmp as $option) {
          $option = trim($option);
          $options[$option] = $option;
        }
        $form[$search_type][$row['category']][$row['name']] = array(
          '#type' => 'select',
          '#title' => $row['title'],
          '#options' => $options,
          '#default_value' => $profile_field_values[$row['name']],
        );
      }
      else {
        $form[$search_type][$row['category']][$row['name']] = array(
          '#type' => $row['type'],
          '#title' => $row['title'],
          '#default_value' => $profile_field_values[$row['name']],
        );
      }
      $previous_category = $row['category'];
      $form_state['profile_field_names'][$row['name']] = $row['type'];
    }
  }

  $form[$search_type]['submit'] = array(
    '#type' => 'submit',
    '#value' => t(ucwords($search_type) . ' search'),
  );
  $form['#method'] = 'GET';
//  $form['#submit'][] = 'tcprofile_search_' . $search_type . '_submit';
//  $form['#validate'][] = 'tcprofile_search_' . $search_type . '_validate';
  return $form;
} // function tcprofile_search_get_search_form

/**
 * Browse all members by paging
 */
function tcprofile_search_browse_member() {
  $sql = "SELECT DISTINCT u.uid, u.name, u.status, u.created, u.access FROM {users} u LEFT JOIN {users_roles} ur ON u.uid = ur.uid WHERE u.uid != 1 AND u.uid != 0 ";
  $sql_count = "SELECT COUNT(DISTINCT u.uid) FROM {users} u LEFT JOIN {users_roles} ur ON u.uid = ur.uid WHERE u.uid != 1 AND u.uid != 0 ";
  return _get_table_list($sql, $sql_count, TRUE, TRUE, '');
} // function tcprofile_search_browse_member

/**
 *
 * @param String $sql
 * @param String $sql_count
 * @param Boolean $and_match
 * @param Boolean $result_page
 * @param String $search_type
 * @return String $output
 */
function _get_table_list($sql, $sql_count, $and_match, $result_page, $search_type = 'general') {
  if ($and_match) {
    global $user;
    if ($search_type == '' && user_access('view advanced tc profile search', $user))
      $search_type = 'advanced';
    else
      $search_type = 'general';

    // get passed parameter value for the fields
    $profile_field_values = $_GET;

    // only one order: Member for, get sort=asc&order=Member+for
    $query_order = isset($profile_field_values['sort']) ? $profile_field_values['sort'] : 'desc';
    if (strtoupper($query_order) == 'DESC' || strtoupper($query_order) == 'ASC') {
      $query_order = ' ORDER BY u.created ' . strtoupper($query_order);
      $sql .= $query_order;
      $sql_count .= $query_order;
    }

    $header = array(
      array('data' => t('Username'), 'field' => 'u.name'),
      array('data' => t('Status'), 'field' => 'u.status'),
      t('Roles'),
      array('data' => t('Member for'), 'field' => 'u.created', 'sort' => 'desc'),
      array('data' => t('Last access'), 'field' => 'u.access'),
    );
    //$sql .= tablesort_sql($header);

    $result = pager_query($sql, 20, 0, $sql_count, array(''));
    $roles = user_roles(TRUE);
    while ($account = db_fetch_object($result)) {
      $uid = $account->uid;
      $account_user = user_load($uid);
      $users_roles = array();
      $roles_result = db_query('SELECT rid FROM {users_roles} WHERE uid = %d', $uid);
      while ($user_role = db_fetch_object($roles_result)) {
        $users_roles[] = $roles[$user_role->rid];
      }
      asort($users_roles);
      $rows[] = array('<a href="/tcprofile/' . $search_type . '_view/' . $uid . '">' . $account_user->name . '</a>', $account->status, theme('item_list', $users_roles), date('F j, Y, g:i a', $account_user->created), date('F j, Y, g:i a', $account_user->access));
    }
  }
  else
    $rows[] = array(array('data' => t('No user found.'), 'colspan' => '5'));

  // only output result for result page not for search page
  if ($result_page) {
    $output = theme('table', $header, $rows);
    $output .= theme('pager', NULL, 20, 0);
  }

  return $output;
} // function _get_table_list

/**
 *
 */
function email_notificaiton_setup_form() {
  global $user;
  $form = array();

  $default_value = NEVER_NOTIFY;
  $result = db_query("SELECT frequency FROM {tcprofile_email_notification_setup} WHERE uid = " . $user->uid);
  while ($row = db_fetch_object($result)) {
    $default_value = $row->frequency;
  }

  $form['email_notification_frequency'] = array(
    '#type' => 'select',
    '#title' => t('Frequency of email notification'),
    '#options' => array(NEVER_NOTIFY => 'NEVER NOTIFY ME', NOTIFY_DAILY => 'DAILY', NOTIFY_WEEKLY => 'WEEKLY', NOTIFY_MONTHLY => 'MONTHLY',  NOTIFY_YEARLY => 'YEARLY'),
    '#default_value' => $default_value
  );

  $form['uid'] = array(
    '#type'          => 'hidden',
    '#title'         => t(''),
    '#default_value' => $user->uid,
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

  $form['cancel'] = array(
    '#type' => 'markup',
    '#value' => l(t('Cancel'), '/'),
  );

  return $form;  
} // function email_notificaiton_setup_form

/**
 *
 */
function email_notificaiton_setup_form_submit($form_id, $form) {
  $form_values = $form['values'];

  $frequency = $form_values['email_notification_frequency'];
  $uid = $form_values['uid'];

  // Delete all previous setup
  $query = "DELETE FROM {tcprofile_email_notification_setup} WHERE uid = " . $uid;
  db_query($query);

  // Insert new one
  $query = "INSERT INTO {tcprofile_email_notification_setup} (uid, frequency) VALUES ($uid, $frequency)";
  db_query($query);

  drupal_set_message(t('Email notification has been updated successfully.'));
} // function email_notificaiton_setup_form_submit
 
/**
 *
 */
function field_visibility_setup_form() {
  global $user;
  $form = array();
  if ($user && $user->uid > 0 && arg(2) && arg(2) == $user->uid) {
    // get profile fields
    $result = db_query("SELECT title, name, type FROM {profile_fields} ORDER BY category, weight");
    $options = array();
    while ($row = db_fetch_array($result)) {
      $options[$row['name']] = $row['title'];
    }

    $previously_selected = array();
    $result = db_query("SELECT * FROM {tcprofile_field_setup} WHERE uid = " . $user->uid);
    while ($row = db_fetch_array($result)) {
      $previously_selected = explode(',', $row['selected_fields']);
    }
   
    // set these fields for user to select visibility
    $form['tcprofile_fieldsetup'] = array(
      '#type'          => 'checkboxes',
      '#title'         => t('Please check the field that you do NOT want to show in public'),
      '#options'       => $options,
      '#default_value' => variable_get('tcprofile_fieldsetup', $previously_selected),
    );

    // set these fields for user to select visibility
    $form['uid'] = array(
      '#type'          => 'hidden',
      '#title'         => t(''),
      '#default_value' => $user->uid,
    );

    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Submit'),
    );
 
    $form['cancel'] = array(
      '#type' => 'markup',
      '#value' => l(t('Cancel'), '/'),
    );

  }
  else {
    $form['featured'] = array(
      '#type' => 'checkboxes',
      '#title' => t('Sorry! You do not have permission to edit this page'),
      '#options' => array(),
      '#default_value' => array(),
    );
  }
  
  return $form;
} // function field_visibility_setup_form

function field_visibility_setup_form_submit($form_id, $form) {
  $form_values = $form['values'];
  $tcprofile_fieldsetup = $form_values['tcprofile_fieldsetup'];
  $uid = $form_values['uid'];
 
  $selected_fields = array();
  foreach($tcprofile_fieldsetup as $key => $value) {
    if ($value)
      $selected_fields[] = $key;
  }
 
  $value_string = @implode(',', $selected_fields);
 
  // Delete all previous selected fields
  $query = "DELETE FROM {tcprofile_field_setup} WHERE uid = " . $uid;
  db_query($query);
 
  // Insert new featured products
  if (count($selected_fields)) {
    $query = "INSERT INTO {tcprofile_field_setup} (uid, selected_fields) VALUES ($uid, '$value_string')";
    db_query($query);
  }

  drupal_set_message(t('Profile field visibility has been updated successfully.'));
} // function field_visibility_setup_form_submit
